import { ModalConfirm, TableLayout } from '@/components';
import {
  backupHistoryList,
  backupHistoryRestore,
  backupHistoryBackup
} from '@/services/backupHistoryMsg';
import { PageContainer, ProFormSelect } from '@ant-design/pro-components';
import { Breadcrumb, Button, Dropdown, message } from 'antd';
import dayjs from 'dayjs';
import { useRef, useState } from 'react';
import { NavLink } from 'react-router-dom';

const BackupsMsg = () => {
  const tableLayoutRef = useRef<any>(null);
  const [paginationTotal, setPaginationTotal] = useState(0);
  const [modItem, setModItem] = useState<any>({});
  const modalConfirmRef = useRef<any>(null);

  const getTableData = async (params?: any) => {
    const res = await backupHistoryList(params);
    if (res?.code === 200) {
      setPaginationTotal(res.total);
      return res.rows;
    }
    return [];
  };

  const columns: any = [
    // 搜索
    {
      dataIndex: 'status',
      hideInTable: true,
      renderFormItem: () => {
        return (
          <ProFormSelect
            name="status"
            label="备份状态"
            placeholder="请选择备份状态"
            options={[
              { label: '备份中', value: 0 },
              { label: '备份成功', value: 1 },
              { label: '备份失败', value: 2 },
            ]}
          />
        );
      },
    },
    {
      dataIndex: 'type',
      hideInTable: true,
      renderFormItem: () => {
        return (
          <ProFormSelect
            name="type"
            label="备份类型"
            placeholder="请选择备份类型"
            options={[
              { label: 'MySQL', value: 'MySQL' },
              { label: 'InfluxDB', value: 'InfluxDB' },
            ]}
          />
        );
      },
    },
    // 表格
    {
      title: '备份类型',
      dataIndex: 'type',
      hideInSearch: true,
      width: 180,
    },
    {
      title: '备份状态',
      dataIndex: 'status',
      hideInSearch: true,
      width: 180,
      render: (_: any, record: any) => (
        <div>
          {record.status == 0 && '备份中'}
          {record.status == 1 && '备份成功'}
          {record.status == 2 && '备份失败'}
        </div>
      ),
    },
    {
      title: '备份文件地址',
      dataIndex: 'filePath',
      hideInSearch: true,
    },
    {
      title: '备份时间',
      dataIndex: 'backupTime',
      hideInSearch: true,
      render: (_: any, record: any) => (
        <div>
          {record.backupTime &&
            dayjs(record.backupTime).format('YYYY-MM-DD HH:mm:ss')}
        </div>
      ),
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      width: 120,
      fixed: 'right',
      render: (_: any, record: any) => (
        <div className="custom-table-option">
          {record.status == 1 ? (
            <a onClick={() => handleOption(record, 'backupHistoryRestore')}>
              恢复备份
            </a>
          ) : (
            '-'
          )}
        </div>
      ),
    },
  ];

  // 操作栏操作
  const handleOption = (row: any, key: string) => {
    setModItem({
      ...row,
      modKey: key,
    });
    if (key === 'backupHistoryRestore') {
      modalConfirmRef?.current?.handleModalShow('确认恢复备份吗?');
    }else if(key === 'backupHistoryBackup'){
      modalConfirmRef?.current?.handleModalShow('确认创建备份吗?');
    }
  };
  const modalSuccessCallback = async () => {
    if (modItem.modKey === 'backupHistoryRestore') {
      const res = await backupHistoryRestore({ backupHistoryId: modItem.id });
      if (res?.code === 200) {
        message.success('操作成功');
        modalConfirmRef?.current?.handleModalShow()
        tableLayoutRef?.current?.tableReload();
      }
    } else if (modItem.modKey === 'backupHistoryBackup') {
      const res = await backupHistoryBackup({ backFlag: modItem.type });
      if (res?.code === 200) {
        message.success('操作成功');
        modalConfirmRef?.current?.handleModalShow()
        tableLayoutRef?.current?.tableReload();
      }
    }
  };
  return (
    <PageContainer
      header={{
        title: <></>,
        ghost: true,
        breadcrumbRender: (route: any) => {
          return (
            <Breadcrumb
              items={[
                {
                  title: (
                    <div
                      style={{
                        display: 'flex',
                        alignContent: 'center',
                      }}
                    >
                      <NavLink to="/backupsMsg">备份管理</NavLink>
                      <div
                        className="ant-breadcrumb-separator"
                        aria-hidden="true"
                      >
                        /
                      </div>
                      <div>备份列表</div>
                    </div>
                  ),
                },
              ]}
            ></Breadcrumb>
          );
        },
      }}
    >
      <TableLayout
        ref={tableLayoutRef}
        getTableData={getTableData}
        headerTitle="备份管理"
        toolBarRender={() => (
          <Dropdown
            menu={{
              items: [
                {
                  key: '1',
                  label: (
                    <div
                      onClick={() =>
                        handleOption(
                          {
                            type: 1,
                          },
                          'backupHistoryBackup',
                        )
                      }
                    >
                      MySQL
                    </div>
                  ),
                },
                {
                  key: '2',
                  label: (
                    <div
                      onClick={() =>
                        handleOption(
                          {
                            type: 2,
                          },
                          'backupHistoryBackup',
                        )
                      }
                    >
                      InfluxDB
                    </div>
                  ),
                },
              ],
            }}
            placement="bottomRight"
            arrow
          >
            <Button className="base-button" type="primary">
              新增备份
            </Button>
          </Dropdown>
        )}
        columns={columns}
        rowKey={'id'}
        pagination={{
          total: paginationTotal,
        }}
      />
      {/* 确认弹层 */}
      <ModalConfirm
        ref={modalConfirmRef}
        successCallback={modalSuccessCallback}
      />
    </PageContainer>
  );
};

export default BackupsMsg;
